package com.rech.xbexpress3;

import com.rech.utils.LogUtil;
import com.rech.utils.OtherUtil;
import com.rech.xbexpress3.R;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.content.Context;

import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;

import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.Switch;
import android.widget.Toast;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 */
public class Kd4Activity extends AppCompatActivity {
    Map<String, Object> map = new HashMap<>();
    List<Map<String, String>> orderlist = new ArrayList();
    /**
     * Whether or not the system UI should be auto-hidden after
     * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
     */
    private static final boolean AUTO_HIDE = true;
    private long mLastClickTime = 0;
    public static final long TIME_INTERVAL = 3000L;
    /**
     * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
     * user interaction before hiding the system UI.
     */
    private static final int AUTO_HIDE_DELAY_MILLIS = 3000;

    /**
     * Some older devices needs a small delay between UI widget updates
     * and a change of the status and navigation bar.
     */
    private static final int UI_ANIMATION_DELAY = 300;
    private final Handler mHideHandler = new Handler();

    private final Runnable mHidePart2Runnable = new Runnable() {
        @SuppressLint("InlinedApi")
        @Override
        public void run() {
            // Delayed removal of status and navigation bar


        }
    };
    private final Runnable mShowPart2Runnable = new Runnable() {
        @Override
        public void run() {
            // Delayed display of UI elements
            ActionBar actionBar = getSupportActionBar();
            if (actionBar != null) {
                actionBar.show();
            }
        }
    };
    private boolean mVisible;
    private final Runnable mHideRunnable = new Runnable() {
        @Override
        public void run() {
            hide();
        }
    };

    private LinearLayout ll_no_data;
    private TextView djs ;
    private Timer countTimer;
    private int jjcount = 100;
    /**
     * Touch listener to use for in-layout UI controls to delay hiding the
     * system UI. This is to prevent the jarring behavior of controls going away
     * while interacting with activity UI.
     */
    private final View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (AUTO_HIDE) {
                delayedHide(AUTO_HIDE_DELAY_MILLIS);
            }
            return false;
        }
    };

    @Override
    public void onConfigurationChanged(Configuration newConfig)
    {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedPreferences sharedPreferences = getSharedPreferences("xbbox", Context.MODE_PRIVATE);
        String orientation = sharedPreferences.getString("Orientation","");
        if (orientation.equals("landscape")) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }

        setContentView(R.layout.activity_kd4);

        mVisible = true;getSupportActionBar().hide();
        djs = findViewById(R.id.tv_djs);
        ll_no_data = findViewById(R.id.ll_no_data);
        //eventbus
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        String username = sharedPreferences.getString("kd_username","");
        new FetchOrderListTask(username).execute();
        //initData(this);
        TextView kd4_qx = (TextView) findViewById(R.id.tv_back);
        kd4_qx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                long nowTime = System.currentTimeMillis();

                if (nowTime - mLastClickTime > TIME_INTERVAL) {
                    mLastClickTime = nowTime;
                    Intent intent = new Intent();
                    //intent.putExtra("sn", resultString);
                    setResult(4008, intent);
                    Exit();
                    finish();

                }
            }
        });


        countTimer=new Timer();
        countTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                jjcount--;
                //djs.setText(String.valueOf(OtherUtil.jjcount));
                Message message = new Message();
                message.what=20000;
                EventBus.getDefault().post(message);
                if(jjcount < 1){
                    Intent intent = new Intent();
                    //intent.putExtra("sn", resultString);
                    setResult(4008, intent);
                    Exit();
                    finish();
                }

            }
        },0,1000);

        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        TextView tv_version = findViewById(R.id.tv_version);
        TextView tv_waiter = findViewById(R.id.tv_waiter);
        try {
            tv_version.setText("v" + OtherUtil.getVersion(this));
        } catch (Exception e) {
            e.printStackTrace();
        }
        String phone = sharedPreferences.getString("CabinetType_phone","");
        tv_waiter.setText("客服电话:" + phone);
    }

    private void Exit(){
        EventBus.getDefault().unregister(this);
    }
    @Override
    protected void onDestroy() {

        super.onDestroy();
    }
    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

        // Trigger the initial hide() shortly after the activity has been
        // created, to briefly hint to the user that UI controls
        // are available.
        delayedHide(100);
    }

    private void toggle() {
        if (mVisible) {
            hide();
        } else {
            show();
        }
    }

    private void hide() {
        // Hide UI first
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        mVisible = false;


    }

    @SuppressLint("InlinedApi")
    private void show() {
        mVisible = true;


    }

    /**
     * Schedules a call to hide() in delay milliseconds, canceling any
     * previously scheduled calls.
     */
    private void delayedHide(int delayMillis) {
        mHideHandler.removeCallbacks(mHideRunnable);
        mHideHandler.postDelayed(mHideRunnable, delayMillis);
    }
    private void initData(Kd4Activity activity ){
        if (null != orderlist && orderlist.size() != 0) {
            ll_no_data.setVisibility(View.INVISIBLE);
            SimpleAdapter simpleAdapter = new SimpleAdapter(Kd4Activity.this,
                    orderlist,
                    R.layout.kd4_item_layout,
                    new String[]{"sjh", "jjr","ljm","gmbh"},
                    new int[]{R.id.sjh, R.id.jjr, R.id.ljm, R.id.gmbh});
            //获取ListView
            final ListView lv = findViewById(R.id.kd4_list);
            //将数据和布局关联，就是将数据显示到列表中
            lv.setAdapter(simpleAdapter);
            //添加点击事件
            lv.setOnItemClickListener(new AdapterView.OnItemClickListener(){
                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                        long arg3) {
                    //获得选中项的HashMap对象
                    HashMap<String,String> map=(HashMap<String,String>)lv.getItemAtPosition(arg2);

                    String id=map.get("id");
                    new FetchKDLjmListTask(id).execute();
                }

            });
        } else {
            ll_no_data.setVisibility(View.VISIBLE);
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN,priority = 100,sticky = false)     //在UI线程执行，100  为优先级
    public void onEvent(Message message){
        Intent intent = new Intent();
        switch(message.what){
            case 10408:
                handleKDorderlist(message.obj);
                break;
            case 10409:
                handleKDLjmListTask(message.obj);
                break;
            case 10410:
                Toast.makeText(Kd4Activity.this, "无法获取订单信息", Toast.LENGTH_LONG).show();
                break;
            case 20000:
                handleDJS();
                break;
        }
    }

    private void handleDJS(){
        djs.setText(String.valueOf(jjcount));
    }

    private void handleKDorderlist(Object obj){
        try{
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){
                JSONArray orders = result.getJSONArray("data");
                for(int i=0; i<orders.length(); i++){
                    JSONObject jsonObject1 = orders.getJSONObject(i);
                    String st = jsonObject1.get("status").toString();
                    if(st.equals("0"))
                    {
                        //String value = jsonObject1.get("toname").toString();
                        String value = "";
                        Map<String, String> map1 = new HashMap<>();
                        //map1.put("sjr",value );
                        value = jsonObject1.get("name").toString();
                        map1.put("jjr", value);
                        value = jsonObject1.get("phone").toString();
                        map1.put("sjh", value);
                        value = jsonObject1.get("gridnum").toString();
                        map1.put("gmbh", value);
                        value = jsonObject1.get("id").toString();
                        map1.put("id", value);
                        value = jsonObject1.get("expressPassword").toString();
                        map1.put("ljm",value);
                        orderlist.add(map1);
                    }

                }
                initData(this);
//                Intent intent = new Intent();
//                //intent.putExtra("sn", resultString);
//                setResult(4006, intent);
//                finish();
            }else{
                /*View cv = getWindow().getDecorView();
                AlertDialog.Builder adbuilder = new AlertDialog.Builder(cv.getContext());
                adbuilder.setTitle(result.getString("msg"));
                adbuilder.setMessage("2秒后自动关闭！");
                adbuilder.setCancelable(true);
                final AlertDialog dlg = adbuilder.create();
                dlg.show();
                final Timer t = new Timer();
                t.schedule(new TimerTask() {
                    public void run() {
                        dlg.dismiss();
                        t.cancel();
                    }
                }, 2000);*/

            }

        }catch(Exception e){
            View cv = getWindow().getDecorView();
            AlertDialog.Builder adbuilder = new AlertDialog.Builder(cv.getContext());
            adbuilder.setTitle("网络异常");
            adbuilder.setMessage("2秒后自动关闭！");
            adbuilder.setCancelable(true);
            final AlertDialog dlg = adbuilder.create();
            dlg.show();
            final Timer t = new Timer();
            t.schedule(new TimerTask() {
                public void run() {
                    dlg.dismiss();
                    t.cancel();
                }
            }, 2000);
        }
    }
    private void handleKDLjmListTask(Object obj)
    {
        try{
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){

                String id = result.getJSONObject("data").getString("id");
                String name = result.getJSONObject("data").getString("name");
                String phone = result.getJSONObject("data").getString("phone");
                String toname = result.getJSONObject("data").getString("toname");
                String cardid = result.getJSONObject("data").getString("cardid");
                String exp_type = result.getJSONObject("data").getString("exp_type");
                String packageid = result.getJSONObject("data").getString("packageid");
                String gridnum = result.getJSONObject("data").getString("gridnum");
                SharedPreferences.Editor editor = getSharedPreferences("xbbox",MODE_PRIVATE).edit();
                editor.putString("kd_lj_id",id);
                editor.putString("kd_lj_name",name);
                editor.putString("kd_lj_phone",phone);
                editor.putString("kd_lj_toname",toname);
                editor.putString("kd_lj_cardid",cardid);
                editor.putString("kd_lj_exp_type",exp_type);
                editor.putString("kd_lj_packageid",packageid);
                editor.putString("kd_gridnum",gridnum);
                editor.apply();


                Intent intent = new Intent();
                //intent.putExtra("sn", resultString);
                intent.putExtra("kd_lj_name", name);
                intent.putExtra("kd_lj_cardid", cardid);
                LogUtil.getInstance().info(OtherUtil.getCurrentTime()+"Kd4Activity揽件列表揽件:"+ "name " + name + "cardid " + cardid );
                setResult(4006, intent);
                Exit();
                finish();
            }else{
                View cv = getWindow().getDecorView();
                AlertDialog.Builder adbuilder = new AlertDialog.Builder(cv.getContext());
                adbuilder.setTitle(result.getString("msg"));
                adbuilder.setMessage("2秒后自动关闭！");
                adbuilder.setCancelable(true);
                final AlertDialog dlg = adbuilder.create();
                dlg.show();
                final Timer t = new Timer();
                t.schedule(new TimerTask() {
                    public void run() {
                        dlg.dismiss();
                        t.cancel();
                    }
                }, 2000);

            }

        }catch(Exception e){
            View cv = getWindow().getDecorView();
            AlertDialog.Builder adbuilder = new AlertDialog.Builder(cv.getContext());
            adbuilder.setTitle("网络异常");
            adbuilder.setMessage("2秒后自动关闭！");
            adbuilder.setCancelable(true);
            final AlertDialog dlg = adbuilder.create();
            dlg.show();
            final Timer t = new Timer();
            t.schedule(new TimerTask() {
                public void run() {
                    dlg.dismiss();
                    t.cancel();
                }
            }, 2000);
        }
    }
}
